import Vue from 'vue'
import App from './App.vue'
import 'element-ui/lib/theme-chalk/index.css';
import '@/assets/css/web.css';
import ElementUI from 'element-ui'
import router from '@/router/index.js'
import api from '@/api/index.js'
import '@/assets/js/web.js'
import Vuex from 'vuex'
import VueAwesomeSwiper from 'vue-awesome-swiper'
import 'swiper/dist/css/swiper.css'
import Echarts from 'echarts'
import '@/assets/js/directives.js'

Vue.prototype.ImgPath = 'http://hgh-oss.oss-cn-beijing.aliyuncs.com/'
// Vue.prototype.ImgPath = 'http://103.254.68.115/'
Vue.config.productionTip = false
Vue.prototype.HOST = '/api'
Vue.prototype.$http = api;
Vue.use(Vuex)
Vue.use(ElementUI)
Vue.use(VueAwesomeSwiper)
Vue.prototype.$echarts = Echarts

const store = new Vuex.Store({
	state: {
		token:localStorage.getItem('token') || '',
	},
	mutations: {
		// 登录成功将, token保存在localStorage中
        LOGIN: (state, data) => {
            localStorage.token = data;
            state.token = data;
        },
        // 退出登录将, token清空
        LOGOUT: (state) => {
            localStorage.removeItem('token');
            state.token = null
        }
	},
	actions: {

	}
})

Number.prototype.toFixed=function(len)
{
var add = 0;
var s,temp;
var s1 = this + "";
var start = s1.indexOf(".");
if(s1.substr(start+len+1,1)>=5)add=1;
var temp = Math.pow(10,len);
s = Math.floor(this * temp) + add;
return s/temp;
}

router.beforeEach((to,from,next)=>{
	if (to.meta.title) {
		document.title = to.meta.title
	}
	var token = localStorage.getItem('token')
	var refreshToken = localStorage.getItem('refreshToken')
	var expiryTime = localStorage.getItem("expiryTime")
	var isexpiryTime = expiryTime != null && new Date().getTime() < expiryTime
	// if(!isexpiryTime){
    //     console.log(new Date().getTime() +"<" + expiryTime +" =" + isexpiryTime)
    // }
	if(to.matched.some(record=>record.meta.requiresAuth)){
		if(token && isexpiryTime){
			next()
		}else if(token && !isexpiryTime){ //已过期刷新token
			// 判断当前是否有登录的权限
			api.get("/api/refreshToken", {token:token,refreshToken:refreshToken}, function(res) {
				// console.log(res)
				if(res.code == "0000"){
					localStorage.setItem("token",res.data.token)
					localStorage.setItem("expiryTime",res.data.expiryTime)
					localStorage.setItem("refreshToken",res.data.refreshToken)
				}else{
					localStorage.setItem("token",'')
					next({
						path: '/login'
					})
				}
			})
		}else{
			localStorage.setItem("token",'')
			next({
				path: '/login'
			})
		}
	}else{
		next()
	}
})

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
